﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Elysium.Notifications;

namespace WGM
{
    public partial class PageBackup : Page
    {
        public PageBackup()
        {
            InitializeComponent();
        }

        string savepath = "";
        string gamename = "";

        private void button_backup_Click(object sender, RoutedEventArgs e)
        {
            listbox_log.Items.Clear();
            button_backup.IsEnabled = false;
            pb_backup.Value = 0;
            pb_backup_running.Visibility = Visibility.Visible;

            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");

            Task backgroundDBTask = Task.Factory.StartNew(() =>
            {
                string sql = "SELECT * FROM gamecentral ORDER BY gamename";
                OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

                this.Dispatcher.Invoke((Action)(() =>
                {
                    listbox_log.Items.Add("Backup to " + Properties.Settings.Default.backuppath + " has started");
                    NotificationManager.TryPushAsync("Backup to " + Properties.Settings.Default.backuppath, "Has been started");
                    listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                    listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                    listbox_log.Items.Add("");
                    listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                    listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                }));

                try
                {
                    while (reader.Read())
                    {
                        if (reader.GetString(2).ToString() != "NOT SET")
                        {
                            gamename = reader.GetString(1).ToString();
                            savepath = reader.GetString(2).ToString();

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                listbox_log.Items.Add("Backup of " + gamename + " was started from " + savepath);
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                            }));

                            DirectoryCopy(savepath, Properties.Settings.Default.backuppath + @"\" + gamename + @"\", true);

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                listbox_log.Items.Add("Backup of " + gamename + " was completed successfully");
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                                listbox_log.Items.Add("");
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                            }));

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                pb_backup.Value++;
                            }));
                        }
                    }
                }
                catch (Exception ex)
                { Console.WriteLine(ex.Message); return; }

                finally
                {
                    reader.Close(); conn.Close();

                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                        listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                        listbox_log.Items.Add("Backup was completed successfully");
                        listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                        listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                        NotificationManager.TryPushAsync("Status", "Backup was completed successfully");
                        button_backup.IsEnabled = true;
                    }));
                }
            });

            backgroundDBTask.ContinueWith((t) =>
            {
                pb_backup.Value = pb_backup.Maximum;
                pb_backup_running.Visibility = Visibility.Hidden;
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                if (System.IO.Path.Combine(file.Name) != "Thumbs.db")
                {
                    string temppath = System.IO.Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                }
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = System.IO.Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }

        private void page_backup_Loaded(object sender, RoutedEventArgs e)
        {
            pb_backup.Maximum = 0;

            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");

            Task backgroundDBTask = Task.Factory.StartNew(() =>
            {
                string sql = "SELECT * FROM gamecentral ORDER BY gamename";
                OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

                try
                {
                    while (reader.Read())
                    {
                        if (reader.GetString(2).ToString() != "NOT SET")
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                listbox_gamelist.Items.Add(reader.GetString(1).ToString());
                                pb_backup.Maximum++;
                            }));
                        }
                    }
                }
                catch (Exception ex)
                { Console.WriteLine(ex.Message); return; }

                finally
                {
                    reader.Close(); conn.Close();
                }
            });
        }

        private void menuitem_selected_Click(object sender, RoutedEventArgs e)
        {
            listbox_log.Items.Clear();
            button_backup.IsEnabled = false;
            pb_backup.Value = 0;
            pb_backup_running.Visibility = Visibility.Visible;

            string gamename = listbox_gamelist.SelectedItem.ToString();

            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");

            Task backgroundDBTask = Task.Factory.StartNew(() =>
            {
                string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";
                OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

                this.Dispatcher.Invoke((Action)(() =>
                {
                    listbox_log.Items.Add("Backup to " + Properties.Settings.Default.backuppath + " has started");
                    listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                    listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                    listbox_log.Items.Add("");
                    listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                    listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                }));

                try
                {
                    while (reader.Read())
                    {
                        if (reader.GetString(2).ToString() != "NOT SET")
                        {
                            gamename = reader.GetString(1).ToString();
                            savepath = reader.GetString(2).ToString();

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                listbox_log.Items.Add("Backup of " + gamename + " was started from " + savepath);
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                            }));

                            DirectoryCopy(savepath, Properties.Settings.Default.backuppath + @"\" + gamename + @"\", true);

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                listbox_log.Items.Add("Backup of " + gamename + " was completed successfully");
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                                listbox_log.Items.Add("");
                                listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                                listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                            }));

                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                pb_backup.Value++;
                            }));
                        }
                    }
                }
                catch (Exception ex)
                { Console.WriteLine(ex.Message); return; }

                finally
                {
                    reader.Close(); conn.Close();

                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                        listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                        listbox_log.Items.Add("Backup was completed successfully");
                        listbox_log.SelectedIndex = listbox_log.Items.Count - 1;
                        listbox_log.ScrollIntoView(listbox_log.Items[listbox_log.SelectedIndex]);
                        button_backup.IsEnabled = true;
                    }));
                }
            });

            backgroundDBTask.ContinueWith((t) =>
            {
                pb_backup.Value = pb_backup.Maximum;
                pb_backup_running.Visibility = Visibility.Hidden;
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
}
